package com.xmg.leetCode;

import java.util.Arrays;

/**
 * @Author: mazhongqing
 * @Date: 2021/3/16 16:33
 */
public class No16 {
    public static void main(String[] args) {
        System.out.println(Solution16.threeSumClosest(new int[]{1,1,1,1},0));
    }
}

class Solution16 {
    public static int threeSumClosest(int[] nums, int target) {
        int res = 3 * 10 *10 * 10;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length-2; i++) {
            int left = i+1;
            int right = nums.length-1;

            while (left<right){
                int sum = nums[i]+nums[left]+nums[right];
                if(sum==target){
                    return sum;
                }else if(sum<target){
                    left++;
                }else{
                    right--;
                }
                if(Math.abs(sum-target)<Math.abs(res-target)){
                    res = sum;
                }
            }

        }
        return res;
    }
}
